<template>
  <div class="course-list-container">
    <div class="header">
      <h2>课程管理</h2>
      <div class="actions">
        <el-input
          v-model="searchQuery"
          placeholder="搜索课程..."
          :prefix-icon="Search"
          clearable
          @clear="handleSearch"
          @input="handleSearch"
          class="search-input"
        />
        <el-button type="primary" @click="handleAdd">
          <el-icon><Plus /></el-icon>添加课程
        </el-button>
        <el-button type="success" @click="$router.push('/back/courses/import')">
          <el-icon><Upload /></el-icon>批量导入
        </el-button>
      </div>
    </div>

    <el-table
      v-loading="loading"
      :data="courseList"
      border
      style="width: 100%"
    >
      <el-table-column type="expand">
        <template #default="props">
          <div class="course-detail">
            <div class="detail-section">
              <h4>基本信息</h4>
              <div class="detail-item">
                <span class="label">课程标题：</span>
                <span>{{ props.row.title }}</span>
              </div>
              <div class="detail-item" v-if="props.row.subtitle">
                <span class="label">副标题：</span>
                <span>{{ props.row.subtitle }}</span>
              </div>
              <div class="detail-item" v-if="props.row.description">
                <span class="label">描述：</span>
                <span>{{ props.row.description }}</span>
              </div>
              <div class="detail-item">
                <span class="label">课程链接：</span>
                <a :href="props.row.courseUrl" target="_blank" class="link">{{ props.row.courseUrl }}</a>
              </div>
            </div>
            
            <div class="detail-section">
              <h4>其他信息</h4>
              <div class="detail-grid">
                <div class="detail-item">
                  <span class="label">机构：</span>
                  <span>{{ props.row.institution }}</span>
                </div>
                <div class="detail-item">
                  <span class="label">难度：</span>
                  <el-tag :type="getDifficultyType(props.row.difficulty)">
                    {{ props.row.difficulty }}
                  </el-tag>
                </div>
                <div class="detail-item">
                  <span class="label">语言：</span>
                  <span>{{ props.row.language }}</span>
                </div>
                <div class="detail-item">
                  <span class="label">学时：</span>
                  <span>{{ props.row.duration }} 分钟</span>
                </div>
                <div class="detail-item">
                  <span class="label">学科：</span>
                  <span>{{ props.row.subject }}</span>
                </div>
                <div class="detail-item">
                  <span class="label">平台：</span>
                  <span>{{ props.row.platform }}</span>
                </div>
                <div class="detail-item">
                  <span class="label">浏览数：</span>
                  <span>{{ props.row.viewCount }}</span>
                </div>
                <div class="detail-item">
                  <span class="label">热度：</span>
                  <span>{{ props.row.heatScore }}</span>
                </div>
                <div class="detail-item">
                  <span class="label">开课日期：</span>
                  <span>{{ props.row.startDate || '暂无' }}</span>
                </div>
                <div class="detail-item">
                  <span class="label">创建时间：</span>
                  <span>{{ formatDate(props.row.createdTime) }}</span>
                </div>
              </div>
            </div>
          </div>
        </template>
      </el-table-column>
      <el-table-column prop="id" label="ID" width="80" />
      <el-table-column label="封面" width="100">
        <template #default="{ row }">
          <el-image
            :src="row.coverImage"
            fit="cover"
            class="course-cover"
            :preview-src-list="row.coverImage ? [row.coverImage] : []"
          >
            <template #error>
              <div class="image-placeholder">
                <el-icon><Picture /></el-icon>
              </div>
            </template>
          </el-image>
        </template>
      </el-table-column>
      <el-table-column prop="title" label="课程标题" min-width="200" show-overflow-tooltip>
        <template #default="{ row }">
          <span>{{ row.title }}</span>
          <el-link
            type="primary"
            :href="row.courseUrl"
            target="_blank"
            class="external-link"
            :underline="false"
          >
            <el-icon class="link-icon"><Link /></el-icon>
          </el-link>
        </template>
      </el-table-column>
      <el-table-column prop="institution" label="机构" width="150" show-overflow-tooltip />
      <el-table-column prop="categoryName" label="分类" width="120" />
      <el-table-column prop="difficulty" label="难度" width="100">
        <template #default="{ row }">
          <el-tag :type="getDifficultyType(row.difficulty)">
            {{ row.difficulty }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="统计" width="180">
        <template #default="{ row }">
          <div class="stats">
            <el-tooltip content="浏览次数">
              <span><el-icon><View /></el-icon> {{ row.viewCount }}</span>
            </el-tooltip>
            <el-tooltip content="热度分数">
              <span><el-icon><Star /></el-icon> {{ row.heatScore }}</span>
            </el-tooltip>
          </div>
        </template>
      </el-table-column>
      <el-table-column prop="createdTime" label="创建时间" width="180">
        <template #default="{ row }">
          {{ formatDate(row.createdTime) }}
        </template>
      </el-table-column>
      <el-table-column label="操作" fixed="right" width="200">
        <template #default="{ row }">
          <el-button-group>
            <el-button type="primary" @click="handleEdit(row)" :icon="Edit" size="small">
              编辑
            </el-button>
            <el-button type="danger" @click="handleDelete(row)" :icon="Delete" size="small">
              删除
            </el-button>
          </el-button-group>

        </template>
      </el-table-column>
    </el-table>

    <el-pagination
      :current-page="currentPage"
      :page-size="pageSize"
      :total="total"
      :page-sizes="[10, 20, 50, 100]"
      layout="total, sizes, prev, pager, next, jumper"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      @update:current-page="currentPage = $event"
      @update:page-size="pageSize = $event"
      class="pagination"
    />

    <!-- 课程表单对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogType === 'add' ? '添加课程' : '编辑课程'"
      width="700px"
    >
      <el-form
        ref="courseFormRef"
        :model="courseForm"
        :rules="courseRules"
        label-width="100px"
      >
        <el-form-item label="课程标题" prop="title">
          <el-input v-model="courseForm.title" placeholder="请输入课程标题" />
        </el-form-item>
        <el-form-item label="副标题" prop="subtitle">
          <el-input v-model="courseForm.subtitle" placeholder="请输入副标题" />
        </el-form-item>
        <el-form-item label="课程描述" prop="description">
          <el-input
            v-model="courseForm.description"
            type="textarea"
            :rows="3"
            placeholder="请输入课程描述"
          />
        </el-form-item>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="课程分类" prop="categoryId">
              <el-select v-model="courseForm.categoryId" placeholder="请选择课程分类" style="width: 100%">
                <el-option
                  v-for="category in categories"
                  :key="category.id"
                  :label="category.name"
                  :value="category.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="难度级别" prop="difficulty">
              <el-select v-model="courseForm.difficulty" placeholder="请选择难度级别" style="width: 100%">
                <el-option label="初级" value="初级" />
                <el-option label="中级" value="中级" />
                <el-option label="高级" value="高级" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="机构名称" prop="institution">
              <el-input v-model="courseForm.institution" placeholder="请输入机构名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="课程语言" prop="language">
              <el-input v-model="courseForm.language" placeholder="请输入课程语言" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="学科" prop="subject">
              <el-input v-model="courseForm.subject" placeholder="请输入学科" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="平台" prop="platform">
              <el-input v-model="courseForm.platform" placeholder="请输入平台" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="学时(分钟)" prop="duration">
              <el-input-number v-model="courseForm.duration" :min="1" style="width: 100%" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="开课日期" prop="startDate">
              <el-date-picker
                v-model="courseForm.startDate"
                type="date"
                placeholder="请选择开课日期"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="课程链接" prop="courseUrl">
          <el-input v-model="courseForm.courseUrl" placeholder="请输入课程链接" />
        </el-form-item>
        <el-form-item label="课程封面" prop="coverImage">
          <el-upload
            class="cover-uploader"
            :auto-upload="false"
            :show-file-list="false"
            :on-change="handleCoverChange"
            accept="image/*"
          >
            <img v-if="courseForm.coverImage" :src="courseForm.coverImage" class="cover" />
            <div v-else class="cover-placeholder">
              <el-icon><Plus /></el-icon>
              <div class="text">点击上传封面</div>
            </div>
          </el-upload>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit" :loading="submitting">
            确定
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { Search, Plus, Edit, Delete, Picture, View, Star, Upload, Link, ChatDotRound } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import request from '@/utils/request'

// 状态变量
const loading = ref(false)
const submitting = ref(false)
const dialogVisible = ref(false)
const dialogType = ref('add')
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)
const searchQuery = ref('')
const courseList = ref([])
const categories = ref([])

// 表单相关
const courseFormRef = ref(null)
const courseForm = reactive({
  title: '',
  subtitle: '',
  description: '',
  courseUrl: '',
  coverImage: '',
  institution: '',
  difficulty: '',
  duration: 60,
  language: '',
  startDate: null,
  subject: '',
  platform: '',
  categoryId: null
})

// 表单验证规则
const courseRules = {
  title: [
    { required: true, message: '请输入课程标题', trigger: 'blur' },
    { min: 2, max: 100, message: '课程标题长度必须在2到100个字符之间', trigger: 'blur' }
  ],
  courseUrl: [
    { required: true, message: '请输入课程链接', trigger: 'blur' }
  ],
  institution: [
    { required: true, message: '请输入机构名称', trigger: 'blur' },
    { max: 100, message: '机构名称长度不能超过100个字符', trigger: 'blur' }
  ],
  difficulty: [
    { required: true, message: '请选择难度级别', trigger: 'change' }
  ],
  duration: [
    { required: true, message: '请输入学时', trigger: 'blur' },
    { type: 'number', min: 1, message: '学时必须大于0', trigger: 'blur' }
  ],
  language: [
    { required: true, message: '请输入课程语言', trigger: 'blur' },
    { max: 50, message: '课程语言长度不能超过50个字符', trigger: 'blur' }
  ],
  subject: [
    { required: true, message: '请输入学科', trigger: 'blur' },
    { max: 50, message: '学科长度不能超过50个字符', trigger: 'blur' }
  ],
  platform: [
    { required: true, message: '请输入平台', trigger: 'blur' },
    { max: 50, message: '平台长度不能超过50个字符', trigger: 'blur' }
  ],
  categoryId: [
    { required: true, message: '请选择课程分类', trigger: 'change' }
  ]
}

// 防抖函数
const debounce = (fn, delay) => {
  let timer = null
  return (...args) => {
    if (timer) clearTimeout(timer)
    timer = setTimeout(() => {
      fn.apply(this, args)
    }, delay)
  }
}

// 获取课程列表
const fetchCourses = async () => {
  loading.value = true
  try {
    const params = {
      pageNum: currentPage.value,
      pageSize: pageSize.value,
      search: searchQuery.value
    }
    await request.get('/course/page', params, {
      showDefaultMsg: false,
      onSuccess: (res) => {
        courseList.value = res.records||[]
        total.value = res.total||0
      }
    })
  } catch (error) {
    console.error('获取课程列表失败:', error)
  } finally {
    loading.value = false
  }
}

// 获取分类列表
const fetchCategories = async () => {
  try {
    await request.get('/category/all', null, {
      showDefaultMsg: false,
      onSuccess: (res) => {
        categories.value = res
      }
    })
  } catch (error) {
    console.error('获取分类列表失败:', error)
  }
}

// 处理分页
const handleSizeChange = (val) => {
  pageSize.value = val
  fetchCourses()
}

const handleCurrentChange = (val) => {
  currentPage.value = val
  fetchCourses()
}

// 处理搜索
const handleSearch = debounce(() => {
  currentPage.value = 1
  fetchCourses()
}, 300)

// 处理添加课程
const handleAdd = () => {
  dialogType.value = 'add'
  Object.assign(courseForm, {
    title: '',
    subtitle: '',
    description: '',
    courseUrl: '',
    coverImage: '',
    institution: '',
    difficulty: '',
    duration: 60,
    language: '',
    startDate: null,
    subject: '',
    platform: '',
    categoryId: null
  })
  dialogVisible.value = true
}

// 处理编辑课程
const handleEdit = (row) => {
  dialogType.value = 'edit'
  Object.assign(courseForm, {
    id: row.id,
    title: row.title,
    subtitle: row.subtitle,
    description: row.description,
    courseUrl: row.courseUrl,
    coverImage: row.coverImage,
    institution: row.institution,
    difficulty: row.difficulty,
    duration: row.duration,
    language: row.language,
    startDate: row.startDate,
    subject: row.subject,
    platform: row.platform,
    categoryId: row.categoryId
  })
  dialogVisible.value = true
}

// 处理删除课程
const handleDelete = (row) => {
  ElMessageBox.confirm(
    '确定要删除该课程吗？此操作不可恢复。',
    '警告',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(async () => {
    try {
      await request.delete(`/course/${row.id}`, {
        successMsg: '删除成功'
      })
      fetchCourses()
    } catch (error) {
      console.error('删除课程失败:', error)
    }
  })
}

// 处理表单提交
const handleSubmit = () => {
  courseFormRef.value.validate(async (valid) => {
    if (valid) {
      submitting.value = true
      try {
        if (dialogType.value === 'add') {
          await request.post('/course', courseForm, {
            successMsg: '添加成功'
          })
        } else {
          const { createdTime, updatedTime, viewCount, heatScore, ...updateData } = courseForm
          await request.put(`/course/${updateData.id}`, updateData, {
            successMsg: '更新成功'
          })
        }
        dialogVisible.value = false
        fetchCourses()
      } catch (error) {
        console.error('保存课程失败:', error)
      } finally {
        submitting.value = false
      }
    }
  })
}

// 处理封面上传
const handleCoverChange = async (file) => {
  const isImage = file.raw.type.startsWith('image/')
  const isLt2M = file.raw.size / 1024 / 1024 < 2

  if (!isImage) {
    ElMessage.error('封面必须是图片格式!')
    return
  }
  if (!isLt2M) {
    ElMessage.error('封面大小不能超过 2MB!')
    return
  }

  try {
    const formData = new FormData()
    formData.append('file', file.raw)
    
    await request.post('/file/upload/img', formData, {
      headers: {
        'Content-Type': 'multipart/form-data'
      },
      successMsg: '上传成功',
      onSuccess: (res) => {
        courseForm.coverImage = res
      }
    })
  } catch (error) {
    console.error('封面上传失败:', error)
    ElMessage.error('封面上传失败')
  }
}

// 获取难度标签类型
const getDifficultyType = (difficulty) => {
  switch (difficulty) {
    case '初级':
      return 'success'
    case '中级':
      return 'warning'
    case '高级':
      return 'danger'
    default:
      return 'info'
  }
}

// 格式化日期
const formatDate = (date) => {
  if (!date) return '暂无'
  return new Date(date).toLocaleString()
}

// 初始化
onMounted(() => {
  fetchCourses()
  fetchCategories()
})
</script>

<style lang="scss" scoped>
.course-list-container {
  padding: 20px;

  .header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;

    h2 {
      margin: 0;
      font-size: 24px;
      color: var(--el-text-color-primary);
    }

    .actions {
      display: flex;
      gap: 10px;

      .search-input {
        width: 200px;
      }
    }
  }

  .course-cover {
    width: 60px;
    height: 60px;
    border-radius: 4px;
  }

  .image-placeholder {
    width: 60px;
    height: 60px;
    display: flex;
    align-items: center;
    justify-content: center;
    background-color: var(--el-fill-color-light);
    border-radius: 4px;
    color: var(--el-text-color-secondary);
  }

  .stats {
    display: flex;
    gap: 16px;
    color: var(--el-text-color-secondary);

    span {
      display: flex;
      align-items: center;
      gap: 4px;
    }
  }

  .pagination {
    margin-top: 20px;
    display: flex;
    justify-content: flex-end;
  }
}

.cover-uploader {
  :deep(.el-upload) {
    border: 1px dashed var(--el-border-color);
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: var(--el-transition-duration);
    
    &:hover {
      border-color: var(--el-color-primary);
    }
  }

  .cover {
    width: 200px;
    height: 120px;
    display: block;
    object-fit: cover;
  }

  .cover-placeholder {
    width: 200px;
    height: 120px;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    color: var(--el-text-color-secondary);

    .el-icon {
      font-size: 28px;
      margin-bottom: 8px;
    }

    .text {
      font-size: 12px;
    }
  }
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

.course-detail {
  padding: 20px;
  background-color: #f9f9f9;
  
  .detail-section {
    margin-bottom: 20px;
    
    h4 {
      margin-top: 0;
      margin-bottom: 15px;
      color: var(--el-color-primary);
      font-weight: 600;
      border-bottom: 1px solid var(--el-border-color-light);
      padding-bottom: 8px;
    }
    
    .detail-item {
      margin-bottom: 10px;
      line-height: 1.5;
      
      .label {
        font-weight: 600;
        color: var(--el-text-color-regular);
        margin-right: 8px;
      }
      
      .link {
        color: var(--el-color-primary);
        text-decoration: none;
        
        &:hover {
          text-decoration: underline;
        }
      }
    }
    
    .detail-grid {
      display: grid;
      grid-template-columns: repeat(3, 1fr);
      gap: 15px;
      
      @media (max-width: 768px) {
        grid-template-columns: repeat(2, 1fr);
      }
      
      @media (max-width: 480px) {
        grid-template-columns: 1fr;
      }
    }
  }
}

.external-link {
  margin-left: 8px;
  font-size: 16px;
  
  .link-icon {
    vertical-align: middle;
  }
}

.review-btn {
  margin-left: 8px;
}
</style> 